//
//  TripOverViewVC.swift
//  MyImGuider
//
//  Created by 王鹏宇 on 2018/9/20.
//  Copyright © 2018年 王鹏宇. All rights reserved.
//

import UIKit
import MJRefresh

class TripOverViewVC: BaseVC {
    
    @IBOutlet weak var tableView: UITableView!
    
    var pageType:Int = 0;// 1为广告位推来的
    
    private var viewmodel = TripOverViewViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        setupData()
        
        if pageType != 1 {
            
            configNavBar()
        }
    }
    
}
extension TripOverViewVC {
    
    func setupUI(){
        
        self.title = pageType == 1 ? LocalizedString("home_hot") : LocalizedString("my_trip")
        self.tableView.register(UINib(nibName: "TripHeaderCell", bundle: nil), forCellReuseIdentifier: "TripHeaderCell")
        self.tableView.register(UINib(nibName: "TripCityCell", bundle: nil), forCellReuseIdentifier: "TripCityCell")
        self.tableView.register(UINib(nibName: "TripADCell", bundle: nil), forCellReuseIdentifier: "TripADCell")
        
        self.tableView.register(SectionHeaderView.self, forHeaderFooterViewReuseIdentifier: "SectionHeaderView")
        
        self.tableView.rowHeight = UITableView.automaticDimension
        self.tableView.sectionHeaderHeight = UITableView.automaticDimension
        self.tableView.estimatedRowHeight = 2
        self.tableView.estimatedSectionHeaderHeight = 60
        self.tableView.estimatedSectionFooterHeight = 2
        
        self.tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            
            [weak self] in
            guard let `self` = self else { return }
          
            self.viewmodel.reloadData()
        })
    }
    
    func setupData() {
        
        viewmodel.loadFinished = {
            
            [weak self] errmsg in
            guard let `self` = self else { return }
            
            if let errmsg = errmsg {
                
                self.view.makeToast(errmsg)
            }
            
            self.tableView.mj_header.endRefreshing()
            
            self.tableView.reloadData()
        }
        
        viewmodel.loadBegining = {
            
            [weak self] isBegin in
            guard let `self` = self else { return }
            
            if isBegin {
                self.showActivity()
            } else {
                
                self.hiddenActivity()
            }
        }
        
        if viewmodel.tripid == nil {
            
            guard let bestid = TripManager.share.besttripid else {
                
                DispatchQueue.main.after(0.25) {
                    
                    self.goAllTrip(true)
                }
                
                return
            }
            
            viewmodel.tripid = bestid
        }
        
        viewmodel.reloadData()
    }
    
    func configNavBar(){
        
        let leftItem = UIBarButtonItem(image: UIImage(named:"设置"), style: .plain, target: self, action: #selector(goSetVC))
        
        let rightItem = UIBarButtonItem(image: UIImage(named:"历史"), style: .plain, target: self, action: #selector(goAllTrip))
        
        self.navigationItem.leftBarButtonItem = leftItem
        self.navigationItem.rightBarButtonItem = rightItem
        
    }
    
    @objc func goSetVC(){
        
        self.navigationController?.pushViewController(AccountVC(), animated: true)
    }
    
    @objc func goAllTrip(_ isPresent:Bool = false){
        
        let tripListVC = TripListVC()
        tripListVC.complete = {
            
            [weak self] trip in
            guard let `self` = self else { return }
            
            if let old = self.viewmodel.tripid,
                let new = trip?.orderId, old == new {
                
                return
            }
            
            self.viewmodel.tripid = trip?.orderId
            
            self.viewmodel.reloadData()
            
            self.tableView.layoutIfNeeded()
            
            self.tableView.setContentOffset(CGPoint.zero, animated: true)
        }
        
        if isPresent {
            
            self.present(UINavigationController(rootViewController: tripListVC), animated: true, completion: nil)
        } else {
            
            self.navigationController?.pushViewController(tripListVC, animated: true)
        }
    }
}


extension TripOverViewVC: UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return viewmodel.cellType?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if let type = viewmodel.cellType?[section], type == .ad {
            
            return viewmodel.advertisements?.count ?? 0
        }
        
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let type = viewmodel.cellType![indexPath.section]
        
        switch type {
            
        case .card:
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "TripHeaderCell") as! TripHeaderCell
            cell.dataSource = viewmodel.cards
            
            cell.superVC = self
            return cell
        case .city:
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "TripCityCell") as! TripCityCell
            cell.citys = viewmodel.featureCities
            cell.superVC = self
            return cell
        case .ad:
            
            let ad = viewmodel.advertisements?[indexPath.row]
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "TripADCell") as! TripADCell
            cell.ad = ad
            
            return cell
        }
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        
        let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SectionHeaderView") as! SectionHeaderView
        
        let type = viewmodel.cellType![section]
        
        switch type {
            
        case .card:
            
            let att = NSMutableAttributedString()
            
            if let planname = viewmodel.trip?.planName {
                
                att.yy_appendString(planname)
                att.yy_font = UIFont.systemFont(ofSize: 24)
                att.yy_color = kTitleColor
            }
            
            
            var plandate = viewmodel.trip?.planDate("yyyy年MM月dd日")
            
            if AppManager.share.language == .english {
                
                plandate = viewmodel.trip?.planDate("dd MMM yyyy")
            }
            
            if let pd = plandate {
                
                if att.length > 0 {
                    
                    att.yy_appendString("\n")
                }
                
                let att1 = NSMutableAttributedString(string: pd)
                
                att1.yy_font = kFont12
                att1.yy_color = kTitleColor
                
                att.append(att1)
            }
            
            att.yy_lineSpacing = 5
            
            headerView.titleLabel?.attributedText = att
            
            headerView.iconImageView?.image = nil
            headerView.desLabel?.text = nil
            return headerView
        case .city:
            
            headerView.titleLabel?.text = LocalizedString("des_city")
            headerView.iconImageView?.image = nil
            headerView.titleLabel?.font = kFont17
            headerView.titleLabel?.textColor = kTitleColor
            
            headerView.desLabel?.text = LocalizedString("detail")
            headerView.desLabel?.font = kFont14
            headerView.desLabel?.textColor = kContentColor
            
            headerView.headerAction = {
                
                [weak self] in
                guard let `self` = self else { return }
                
                let vc = TripArrangeVC()
                vc.viewmodel.trip = self.viewmodel.trip
                
                self.navigationController?.pushViewController( vc , animated: true)
            }
            
            return headerView
        case .ad:
            
            headerView.titleLabel?.text = LocalizedString("home_hot")
            headerView.iconImageView?.image = nil
            headerView.titleLabel?.font = kFont17
            headerView.titleLabel?.textColor = kTitleColor
            
            //            headerView.desLabel?.text = "查看详情"
            //            headerView.desLabel?.font = kFont14
            //            headerView.desLabel?.textColor = kContentColor
            
            //            headerView.headerAction = {
            //
            //                [weak self] in
            //                guard let `self` = self else { return }
            //
            //                let vc = TripArrangeVC()
            //                vc.viewmodel.trip = self.viewmodel.trip
            //
            //                self.navigationController?.pushViewController( vc , animated: true)
            //            }
            //
            return headerView
        }
    }
    
    //    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    //
    //        return 80
    //    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let type = viewmodel.cellType![indexPath.section]
        
        if type != .ad {
            return
        }
        
        guard let ad = viewmodel.advertisements?[indexPath.row],
            let adtype = ad.adType,
         let detail = ad.adDetail else {
                
                return
        }
        
        switch adtype {
            
        case .website:
            
            let webvc = WebVC(urlstr: detail)
            self.navigationController?.pushViewController(webvc, animated: true)
            
        case .trip:
            
            if let old = self.viewmodel.tripid, old == detail {
                
                return
            }
            
            let tripVC = TripOverViewVC()
            tripVC.viewmodel.tripid = detail
            tripVC.pageType = 1
            
            self.navigationController?.pushViewController(tripVC, animated: true)
            
        case .citytour:
            
            let otherVC = OtherDetailVC()
            otherVC.viewmodel.calendar = ad.lineDetail;
            
            self.navigationController?.pushViewController(otherVC, animated: true)
        }
        
    }
}



